package net.samsb.response;

import android.app.ProgressDialog;
import android.os.Message;
import android.util.Log;
import android.util.TimeUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import net.samsb.BaseApplication;
import net.samsb.log.LogUtils;
import net.samsb.model.HeartbeatEntity;
import net.samsb.model.StudentMsgOrNumEntity;
import net.samsb.model.StudentNumEntity;
import net.samsb.model.WJsonEntity;
import net.samsb.tool.NetWorkUtils;
import net.samsb.tool.ReconnectionWSErrorThread;
import net.samsb.tool.ReconnectionWSThread;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

import static net.samsb.activity.Constants.ERROR;
import static net.samsb.activity.Constants.UPDATE_STUDENT_MSG_OR_NUM_UI;
import static net.samsb.activity.Constants.UPDATE_STUDENT_MSG_UI;
import static net.samsb.activity.Constants.UPDATE_STUDENT_NOT_NAME_UI;
import static net.samsb.activity.Constants.UPDATE_WEATHER_UI;

/**
 * Created by Destiny_hao on 2018/3/26.
 */

public class WebSocketResponseListener extends WebSocketListener {

    private String type;
    private Message message;
    private ProgressDialog waitingDialog;

    public WebSocketResponseListener() {

    }

    public WebSocketResponseListener(ProgressDialog waitingDialog) {
        this.waitingDialog = waitingDialog;
    }

    public WebSocketResponseListener(String type, ProgressDialog waitingDialog) {
        this.type = type;
        this.waitingDialog = waitingDialog;
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);

        BaseApplication.BaseWebSocket = webSocket;

        if (BaseApplication.isReconnect) {
            BaseApplication.isErrorReconnect = false;
        }

        LogUtils.e("WebSocketOnOpen：", "连接成功 ");
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        super.onMessage(webSocket, text);

        if (waitingDialog != null) {
            waitingDialog.dismiss();
        }

        LogUtils.e("WebSocketOnMessage：", text);

        message = BaseApplication.mHandler
                .getHandlerWithName("MainActivity")
                .obtainMessage();

        if (BaseApplication.isFirstOpen && type != null && "test".equals(type)) {

            message.arg2 = -1;
        } else {

            message.arg2 = 1;
        }

        if (text.indexOf("wjson") > 0) {
            JSONObject jsonObject = JSON.parseObject(text);

            JSONObject wjson = jsonObject.getJSONObject("wjson");

            LogUtils.e("WS连接数据textJSON：", wjson.toJSONString());

            WJsonEntity wJsonEntity = JSON.parseObject(wjson.toJSONString(), WJsonEntity.class);

            message.what = UPDATE_WEATHER_UI;
            message.obj = wJsonEntity;
        }

        if (text.indexOf("xm") > 0) {

            Object object = null;

            if (text.indexOf("NOTNAME") > 0) {
                object = JSON.parseObject(text, StudentNumEntity.class);
                message.arg1 = UPDATE_STUDENT_NOT_NAME_UI;
            } else {
                object = JSON.parseObject(text, StudentMsgOrNumEntity.class);
                message.arg1 = UPDATE_STUDENT_MSG_UI;
            }

            message.obj = object;
            message.what = UPDATE_STUDENT_MSG_OR_NUM_UI;
        }

        type = "";

        BaseApplication.mHandler
                .getHandlerWithName("MainActivity")
                .sendMessage(message);

        //第一次获取信息
        if (BaseApplication.isFirstConnect) {

            BaseApplication.isFirstConnect = false;
            BaseApplication.BaseReconnectionWSThread.start();
        }

        //错误重连
        if (BaseApplication.isReconnect) {

            BaseApplication.isReconnect = false;

            BaseApplication.BaseReconnectionWSThread = new ReconnectionWSThread();
            BaseApplication.BaseReconnectionWSThread.start();

            LogUtils.e("thread", "BaseReconnectionWSThread:" + BaseApplication.BaseReconnectionWSThread.isAlive());
        }

        BaseApplication.isErrorReconnect = true;
    }

    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {
        super.onMessage(webSocket, bytes);

        if (waitingDialog != null) {
            waitingDialog.dismiss();
        }
    }

    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        super.onClosing(webSocket, code, reason);

        BaseApplication.BaseWebSocket.close(1000, null);
    }

    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        super.onClosed(webSocket, code, reason);

        BaseApplication.BaseWebSocket.close(1000, null);
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);

        BaseApplication.BaseReconnectionWSThread.interrupt();
        BaseApplication.BaseReconnectionWSThread.isStop = true;

        if (waitingDialog != null) {
            waitingDialog.dismiss();
        }

        LogUtils.e("WS错误", t.getMessage());

        message = BaseApplication.mHandler
                .getHandlerWithName("MainActivity")
                .obtainMessage();

        message.what = ERROR;

        if (t instanceof SocketTimeoutException) {

            //message.obj = "连接超时";

            LogUtils.e("WS连接错误连接超时：", t.getMessage());
        } else if (t instanceof UnknownHostException) {

            //message.obj = "服务器主机未找到";

            LogUtils.e("WS连接错误服务器主机未找到：", t.getMessage());
        } else if ("test".equals(type)) {
            type = "";
            message.obj = "端口错误";
            LogUtils.e("WS错误", "端口错误");

            BaseApplication.mHandler
                    .getHandlerWithName("MainActivity")
                    .sendMessage(message);

            return;
        }

        //其他错误
        else {
            //message.obj = "WS未知错误";

            //LogUtils.e("WS错误", "WS未知错误");

        }

        BaseApplication.isReconnect = true;

        if (BaseApplication.BaseWebSocket != null) {

            try {
                TimeUnit.SECONDS.sleep(10);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (BaseApplication.isErrorReconnect) {
                LogUtils.e("getWebSocketMessage", "ERROR_RECONNECT_重连");
                BaseApplication.BaseWebSocket.close(4444, null);
                BaseApplication.BaseRequestInstance.getWebSocketRequest().getWebSocketMessage(null);
            }
        }

        LogUtils.e("thread_e", "BaseReconnectionWSThread:" + BaseApplication.BaseReconnectionWSThread.isAlive());

        BaseApplication.mHandler
                .getHandlerWithName("MainActivity")
                .sendMessage(message);
    }
}
